// 导入数据库操作模块
const db = require('../db/index')


const updateUserMsgReadList = (msgId, id, readListContent) => {
    var list = JSON.parse(readListContent);
    if (!list) {
        list = [msgId]
    } else {
        list.push(msgId);
    }
    const sql = 'update users set read_list = ? where id = ?';
    db.query(sql, [JSON.stringify(list), id], (err, result) => {
        console.log("update read list", err, result);
    });
}

const updateUsersMsgReadList = async (msgId, msgLevel, msgReceiverId) => {
    if (msgLevel <= 1) {
        const sql = msgLevel == 0 ? 'select id, read_list from users'
            : 'select id, read_list from users where identity <= 1';
        db.query(sql, (err, result) => {
            console.log(result);
            if (err || !result || result.length == 0) {
                console.log(err);
                return;
            }
            result.forEach(item => {
                updateUserMsgReadList(msgId, item.id, item.read_list);
            })
        });
    } else { // 单个用户可见
        const sql = 'select read_list from users where id = ?';
        db.query(sql, msgReceiverId, (err, result) => {
            console.log(result);
            if (err || !result || result.length == 0) {
                console.log(err);
                return;
            }
            updateUserMsgReadList(msgId, result[0].id, result[0].read_list)
        });
    }
}

// 发布消息
exports.publishMessage = (req, res) => {
    const publisherId = req.auth.id;
    console.log("publishMessage publisher id", publisherId);
	const {
		message_title,
        message_content,
        message_level,
        receiver_id
	} = req.body
	const message_publish_time = new Date()
	const sql = 'insert into message set ? '
    const message_receiver_id = receiver_id === void 0 ? -1 : receiver_id
	db.query(sql, {
		message_title,
		message_content,
		message_status:0,
		message_publisher_id:publisherId,
		message_publish_time,
		message_click_number: 0,
		message_receiver_id:-1,
		message_level
	}, (err, result) => {
        console.log(result);
		if (err) return res.cc(err)
        updateUsersMsgReadList(result.insertId, message_level, message_receiver_id);
		res.send({
			status: 0,
			message: '发布消息成功',
			id: result.insertId
		})
	})
}

// 获取公司公告列表
exports.companyMessageList = (req, res) => {
	const sql =
		'select * from message where message_level = 0 and message_status = "0" order by message_publish_time DESC limit 5'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 获取系统消息列表
exports.systemMessageList = exports.companyMessageList;

// 编辑公告
exports.editMessage = (req, res) => {
    // 只允许修改title，content和发布者
	const {
		message_title,
		message_publisher_id,
		message_content,
		id
	} = req.body
    const message_update_time = new Date()
    const sql =
        'update message set message_title = ?,message_publisher_id= ?,message_content = ? ,message_update_time= ? where id = ?'
    db.query(sql, [
        message_title,
        message_publisher_id,
        message_content,
        message_update_time,
        id
    ], (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '编辑消息成功'
        })
    })
}

// 根据发布等级进行获取消息
exports.searchMessageByLevel = (req, res) => {
	const sql = 'select * from message where message_level = ? and message_status = "0"'
	db.query(sql, req.body.message_level, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 获取公告/系统消息
exports.getMessage = (req, res) => {
	const sql = 'select * from message where id = ?'
	db.query(sql, req.body.id, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 更新点击率
exports.updateClick = (req, res) => {
	const {
		id
	} = req.body
	const sql = 'update message set message_click_number = message_click_number + 1 where id = ?'
	db.query(sql, id, (err, result) => {
		if (err) return res.cc(err)
		res.send({
			status: 0,
			message: '点击率增加'
		})
	})
}

// 初次删除
exports.firstDelete = (req, res) => {
	const message_delete_time = new Date()
	const sql = 'update message set message_status = 1 ,message_delete_time = ? where id = ?'
	db.query(sql, [message_delete_time, req.body.id], (err, result) => {
		if (err) return res.cc(err)
		res.send({
			status: 0,
			message: '删除成功'
		})
	})
}


// 获取回收站的列表
exports.recycleList = (req, res) => {
	const sql = 'select * from message where message_status = 1'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 获取回收站总数
exports.getRecycleMessageLength = (req, res) => {
	const sql = 'select * from message where message_status = 1'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send({
			length: result.length
		})
	})
}

// 回收站监听换页
exports.returnRecycleListData = (req, res) => {
	const number = (req.body.pager - 1) * 10
	const sql =
		`select * from message where message_status = 1 ORDER BY message_delete_time limit 10 offset ${number} `
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}


// 还原操作
exports.recover = (req, res) => {
	const message_status = 0
	const message_update_time = new Date()
	const sql = 'update message set message_status = ? ,message_update_time = ? where id = ?'
	db.query(sql, [message_status, message_update_time, req.body.id], (err, result) => {
		if (err) return res.cc(err)
		res.send({
			status: 0,
			message: '还原成功'
		})
	})
}


// 删除操作
exports.deleteMessage = (req, res) => {
	const sql = 'delete from message where id = ?'
	db.query(sql, req.body.id, (err, result) => {
		if (err) return res.cc(err)
		res.send({
			status: 0,
			message: '删除消息成功'
		})
	})
}

// 获取全员公告总数
exports.getCompanyMessageLength = (req, res) => {
	const sql = 'select * from message where message_level = 0'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send({
			length: result.length
		})
	})
}

// 获取管理员可见的消息
exports.getSystemMessageLength = (req, res) => {
	const sql = 'select * from message where message_level = 1'
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send({
			length: result.length
		})
	})
}

// 监听换页返回数据  公司公告列表
// limit 10 为我们要拿到数据 offset 我们跳过多少条数据
exports.returnCompanyListData = (req, res) => {
	const number = (req.body.pager - 1) * 10
	const sql =
		`select * from message where message_level = 0 and message_status = 0 ORDER BY message_publish_time limit 10 offset ${number} `
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}

// 监听换页返回数据  系统消息列表
exports.returnSystemListData = (req, res) => {
	const number = (req.body.pager - 1) * 10
	const sql =
		`select * from message where message_level = 1 and message_status = 0  ORDER BY message_publish_time limit 10 offset ${number} `
	db.query(sql, (err, result) => {
		if (err) return res.cc(err)
		res.send(result)
	})
}